package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("report")
@Slf4j
public class ReportController {
    @DubboReference
    private MemberService memberService;
    @DubboReference
    private OrderService orderService;
    @DubboReference
    private ReportService reportService;

    /**
     * @Author: 位帅帅
     * @Date: 16:09 2021/1/14
     * @Params: []
     * @RerurnType: com.itheima.health.entity.Result
     * @Description: 获取会员报表
    */
    @GetMapping("getMemberReport")
    public Result getMemberReport() {
        Map<String, Object> map = new HashMap<>();
        List<String> months = new ArrayList<>();
        List<Integer> memberCount = null;
        //构造months
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH,-12);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");
        for (int i = 0; i < 12; i++) {
            cal.add(Calendar.MONTH,1);
            months.add(sdf.format(cal.getTime()));
        }
        //构造memberCount
        memberCount = memberService.countByMonth(months);
        //将数据存入map集合
        map.put("months",months);
        map.put("memberCount",memberCount);
        return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }

    /**
     * @Author: 位帅帅
     * @Date: 20:05 2021/1/14
     * @Params: []
     * @RerurnType: com.itheima.health.entity.Result
     * @Description: 获取套餐占比饼图
    */
    @GetMapping("getSetmealReport")
    public Result getSetmealReport() {
        /*"data":{
            "setmealNames":["套餐1","套餐2","套餐3"],
            "setmealCount":[
            {"name":"套餐1","value":10},
            {"name":"套餐2","value":30},
            {"name":"套餐3","value":25}
						   ]
        }*/
        List<String> setmealNames = new ArrayList<>();
        List<Map<String,Object>> setmealCount = orderService.findSetmealCount();
        HashMap<String, Object> map = new HashMap<>();
        map.put("setmealNames",setmealNames);
        map.put("setmealCount",setmealCount);
        return new Result(true,MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
    }

    /**
     * @Author: 位帅帅
     * @Date: 12:24 2021/1/15
     * @Params: []
     * @RerurnType: com.itheima.health.entity.Result
     * @Description: 获取运营数据
    */
    @GetMapping("getBusinessReportData")
    public Result getBusinessReportData() {
        Map<String,Object> map = reportService.getBusinessReportData();
        log.info("[运营数据-查询]map: {}",map);
        return new Result(true,MessageConst.GET_BUSINESS_REPORT_SUCCESS,map);
    }

    /**
     * @Author: 位帅帅
     * @Date: 22:26 2021/1/15
     * @Params: []
     * @RerurnType: com.itheima.health.entity.Result
     * @Description: 导出运营数据
    */
    @GetMapping("exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response) {
        try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("static/template/report_template.xlsx")) {
            Map<String, Object> map = reportService.getBusinessReportData();
            log.info("[运营数据-导出]map: {}",map);
            //取出日期数据
            String reportDate = String.valueOf(map.get("reportDate"));
            //取出会员数据
            Long totalMember = Long.valueOf(map.get("totalMember").toString());
            Long todayNewMember = Long.valueOf(map.get("todayNewMember").toString());
            Long thisWeekNewMember = Long.valueOf(map.get("thisWeekNewMember").toString());
            Long thisMonthNewMember = Long.valueOf(map.get("thisMonthNewMember").toString());
            //取出预约数据
            Long todayOrderNumber = Long.valueOf(map.get("todayOrderNumber").toString());
            Long thisWeekOrderNumber = Long.valueOf(map.get("thisWeekOrderNumber").toString());
            Long thisMonthOrderNumber = Long.valueOf(map.get("thisMonthOrderNumber").toString());
            //取出到诊数据
            Long todayVisitsNumber = Long.valueOf(map.get("todayVisitsNumber").toString());
            Long thisWeekVisitsNumber = Long.valueOf(map.get("thisWeekVisitsNumber").toString());
            Long thisMonthVisitsNumber = Long.valueOf(map.get("thisMonthVisitsNumber").toString());
            //取出热门套餐
            List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");
            //创建文件及工作表
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = workbook.getSheetAt(0);
            //将数据存入工作表
            //日期
            sheet.getRow(2).getCell(5).setCellValue(reportDate);
            //会员
            sheet.getRow(4).getCell(5).setCellValue(todayNewMember);
            sheet.getRow(4).getCell(7).setCellValue(totalMember);
            sheet.getRow(5).getCell(5).setCellValue(thisWeekNewMember);
            sheet.getRow(5).getCell(7).setCellValue(thisMonthNewMember);
            //预约
            sheet.getRow(7).getCell(5).setCellValue(todayOrderNumber);
            sheet.getRow(8).getCell(5).setCellValue(thisWeekOrderNumber);
            sheet.getRow(9).getCell(5).setCellValue(thisMonthOrderNumber);
            //到诊
            sheet.getRow(7).getCell(7).setCellValue(todayVisitsNumber);
            sheet.getRow(8).getCell(7).setCellValue(thisWeekVisitsNumber);
            sheet.getRow(9).getCell(7).setCellValue(thisMonthVisitsNumber);
            //热门套餐
            int rownum = 12;
            for (Map setmeal : hotSetmeal) {
                sheet.getRow(rownum).getCell(4).setCellValue(String.valueOf(setmeal.get("name")));
                sheet.getRow(rownum).getCell(5).setCellValue(String.valueOf(setmeal.get("setmeal_count")));
                sheet.getRow(rownum).getCell(6).setCellValue(String.valueOf(setmeal.get("proportion")));
                sheet.getRow(rownum).getCell(7).setCellValue(String.valueOf(setmeal.get("remark")));
                rownum++;
            }
            //设置返回格式
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition","attachment;fileName=" + reportDate + "_report.xlsx");
            workbook.write(outputStream);
            return null;
            /*reportData:{
                reportDate:null,
                todayNewMember:0,totalMember:0,
                thisWeekNewMember:0,thisMonthNewMember:0,
                todayOrderNumber:0,todayVisitsNumber:0,
                thisWeekOrderNumber:0,thisWeekVisitsNumber:0,
                thisMonthOrderNumber:0,thisMonthVisitsNumber:0,
                hotSetmeal :[
                    {name:'阳光爸妈',setmeal_count:200,proportion:0.222,remark:""},
                ]
            }*/
        }catch (IOException e) {
            log.error("",e);
            return new Result(false,MessageConst.ACTION_FAIL);
        }
    }

}
